package com.tbl.modules.wms.controller.move;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.entity.move.MoveStorage;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import com.tbl.modules.wms.service.baseinfo.WarehouseService;
import com.tbl.modules.wms.service.move.MoveStorageDetailService;
import com.tbl.modules.wms.service.move.MoveStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 移库处理--移库模块
 * @author 70486
 */
@Controller
@RequestMapping("/move")
public class MoveController extends AbstractController {

    /**
     * 移库处理-移库主表
     */
    @Autowired
    private MoveStorageService moveStorageService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 仓库服务类
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 厂区
     */
    @Autowired
    private FactoryAreaService factoryAreaService;
    /**
     * 移库单明细
     */
    @Autowired
    private MoveStorageDetailService moveStorageDetailService;

    /**
     * 跳转到列表页
     * @return ModelAndView
     */
    @RequestMapping("/moveListView")
    public ModelAndView moveListView() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/move/moveinfo/moveinfo_list");
        return mv;
    }


    /**
     * 移库单管理列表页数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/movePageList.do")
    @ResponseBody
    public Map<String, Object> movePageList(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(3);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = moveStorageService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击新增跳转到新增页面
     * @return MpdelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("userName", getSessionUser().getUsername());
        mv.addObject("moveStorageId", -1);
        mv.setViewName("techbloom/move/moveinfo/moveinfo_add");
        return mv;
    }

    /**
     * 移库单管理根据主键获取到详情的列表
     * @param id 移库单主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/detailList.do")
    @ResponseBody
    public Map<String, Object> detailList(Integer id) {
        Map<String, Object> map = new HashMap<>(2);
        PageTbl page = this.getPage();
        PageUtils utils = moveStorageService.getPageDetailList(page, id);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 移库单管理点击查看，跳转到详情列表页
     * @param id 移库单主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toInfo.do")
    @ResponseBody
    public ModelAndView toInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", moveStorageService.selectInfoById(id));
        mv.setViewName("techbloom/move/moveinfo/moveinfo_info");
        return mv;
    }	

    /**
     * 点击编辑，跳转到编辑页面
     * @param id 移库单主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/editInfo.do")
    @ResponseBody
    public ModelAndView editInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", moveStorageService.selectInfoById(id));
        mv.setViewName("techbloom/move/moveinfo/moveinfo_edit");
        return mv;
    }

    /**
     * 点击编辑，点击保存  保存主表信息
     * @param moveStorage 移库单
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveMoveStorage")
    @ResponseBody
    public Map<String, Object> saveMoveStorage(MoveStorage moveStorage) {
        Map<String, Object> map = new HashMap<>();
        moveStorage.setUserId(getUserId());
        Long id = moveStorageService.saveMoveStorage(moveStorage);
        map.put("result", true);
        map.put("msg", id > 0 ? "保存成功！" : "保存失败！");
        map.put("allocationId", id);
        return map;
    }

    /**
     * 点击编辑，点击提交，修改状态
     * @param moveStorage 移库单
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/subMoveStorage")
    @ResponseBody
    public Map<String, Object> subMoveStorage(MoveStorage moveStorage) {
        return moveStorageService.subMoveStorage(moveStorage);
    }
    
    /**
     * 点击新增，点击提交，修改状态
     * @param moveStorage 移库单
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/subMoveStorage2")
    @ResponseBody
    public Map<String, Object> subMoveStorage2(MoveStorage moveStorage) {
        return moveStorageService.subMoveStorage2(moveStorage);
    }

    /**
     * 点击编辑，获取质保单号列表(要移库的数据)
     * @param  queryString 查询条件
     * @param warehouseId 仓库主键
     * @param factoryCode 厂区编码
     * @param pageSize 页码
     * @param pageNo 页面编号
     * @param move 新增/编辑 页面标识
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getQaCode")
    @ResponseBody
    public Map<String, Object> getQaCode(String queryString, Long warehouseId, String factoryCode, int pageSize, int pageNo, String move ) {
        Map<String, Object> map = Maps.newHashMap();
        if(StringUtils.isNotEmpty(queryString)){
            map.put("queryString", queryString);
        }
        map.put("warehouseCode", warehouseService.selectById(warehouseId).getCode());
        map.put("factoryCode", "add".equalsIgnoreCase(move)?factoryCode:factoryAreaService.selectById(factoryCode).getCode());
        PageTbl page = this.getPage();
        page.setPagesize(pageSize);
        page.setPageno(pageNo);
        PageUtils utils = moveStorageService.getQaCode(page, map);
        map.put("result", utils.getList() == null ? "" : utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        map.put("msg", "success");
        return map;

    }

    /**
     * 添加、编辑，移库单管理详情添加
     * @param qaCodeIds 详情质保号
     * @param factoryCode 厂区编码‘
     * @param warehouseId 仓库主键
     * @param type 类型：add为新增，update为修改
     * @param moveCode 移库单号
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveMoveStorageDetail")
    @ResponseBody
    public Map<String, Object> saveMoveStorageDetail(String[] qaCodeIds, String factoryCode, Long warehouseId,String type, String moveCode) {
        MoveStorage moveStorage = new MoveStorage();
        if (Constant.PAGE_TYPE_ADD.equals(type)){
            //新增时，moveCode代表移库单号
            if (StringUtils.isEmpty(moveCode)){
                String serial = new DecimalFormat("0000").format(moveStorageService.selectLatestAllocation() + 1);
                moveStorage.setMoveCode("YK" + DateUtils.getDays() + serial);
                Warehouse warehouse = warehouseService.selectById(warehouseId);
                moveStorage.setMoveTime(new Date());
                moveStorage.setWarehouseCode(warehouse.getCode());
                moveStorage.setWarehouseId(warehouse.getId());
                moveStorage.setFactoryCode(factoryCode);
                moveStorage.setUserId(getUserId());
                moveStorageService.insert(moveStorage);

                moveStorageService.updateSerial(serial,Constant.SERIAL_MOVE);
            }else {
                moveStorage = moveStorageService.selectOne(new EntityWrapper<MoveStorage>().eq("MOVECODE", moveCode));
            }
        }else if ("update".equals(type)){
            //修改时，moveCode代表调拨单主键
            moveStorage = moveStorageService.selectById(moveCode);
        }

        Map<String, Object> map = Maps.newHashMap();
        boolean result = moveStorageService.saveMoveStorageDetail(moveStorage.getId(), qaCodeIds);
        map.put("result", result);
        map.put("msg", result?"添加成功！":"添加失败！");
        map.put("id", moveStorage.getId());
        map.put("moveCode", moveStorage.getMoveCode());
        return map;
    }

    /**
     * 点击编辑，删除移库明细数据
     * @param ids 移库详情主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteMoveStorageDetailIds")
    @ResponseBody
    public Map<String, Object> deleteMoveStorageDetailIds(String[] ids) {
        return moveStorageService.deleteMoveStorageDetailIds(ids);
    }

    /**
     * 列表页面点击删除，删除主表和详情的数据
     * @param ids 移库单主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteByIds")
    @ResponseBody
    public Map<String, Object> deleteByIds(String[] ids) {
        return moveStorageService.deleteByIds(ids);
    }

    /**
     * 获取登陆用户所属所有厂区下的所有的仓库
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectWarehouse.do")
    @ResponseBody
    public Map<String, Object> selectWarehouse() {
        Map<String, Object> map = new HashMap<>();
        //okk
        map.put("factoryCode", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        map.put("queryString", request.getParameter("queryString"));
        PageTbl page = this.getPage();
        page.setPageno(Integer.parseInt(request.getParameter("pageNo")));
        PageUtils utils = moveStorageService.selectWarehouse(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>(8);
        //okk
        map.put("org", getSessionUser().getFactoryCode());
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));
        map.put("moveCode", request.getParameter("queryMoveCode"));
        map.put("factoryCode", request.getParameter("queryFactoryCode"));
        map.put("warehouseId", request.getParameter("queryWarehouse"));
        map.put("startTime", request.getParameter("queryStartTime"));
        map.put("endTime", request.getParameter("queryEndTime"));
        map.put("creater", request.getParameter("queryCreater"));

        try {
            String sheetName = "移库单管理" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("moveCode", "移库单号");
                mapFields.put("moveTimeStr", "单据创建时间");
                mapFields.put("warehouseCode", "仓库");
                mapFields.put("factoryName", "厂区");
                mapFields.put("startOutTimeStr", "移库开始时间");
                mapFields.put("endInTimeStr", "移库结束时间");
                mapFields.put("userName", "创建人");
                mapFields.put("moveState", "单据状态");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("moveCode", "移库单号");
                    } else if ("3".equals(s)) {
                        mapFields.put("moveTimeStr", "单据创建时间");
                    } else if ("4".equals(s)) {
                        mapFields.put("warehouseCode", "仓库");
                    } else if ("5".equals(s)) {
                        mapFields.put("factoryName", "厂区");
                    } else if ("6".equals(s)) {
                        mapFields.put("startOutTimeStr", "移库开始时间");
                    } else if ("7".equals(s)) {
                        mapFields.put("endInTimeStr", "移库结束时间");
                    } else if ("8".equals(s)) {
                        mapFields.put("userName", "创建人");
                    } else if ("9".equals(s)) {
                        mapFields.put("moveState", "单据状态");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, moveStorageService.getExcelList(map), mapFields, response, "");
            logService.logInsert("移库单管理导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 移库单明细导出Excel
     * @param  request
     * @param  response
     */
    @RequestMapping(value = "/detailExcel.do", method = RequestMethod.POST)
    @ResponseBody
    public void detailExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>(2);
        map.put("id", request.getParameter("infoid"));
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));

        try {
            String sheetName = "移库单管理" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();

            mapFields.put("qaCode", "质保单号");
            mapFields.put("batchNo", "批次号");
            mapFields.put("materialCode", "物料编码");
            mapFields.put("materialName", "物料名称");
            mapFields.put("drumType", "盘类型");
            mapFields.put("model", "盘规格");
            mapFields.put("meter", "数量");
            mapFields.put("outShelfCode", "移出库位");
            mapFields.put("inShelfCode", "移入库位");
            mapFields.put("stateStr", "状态");
            mapFields.put("moveCode", "移库单号");
            mapFields.put("movetimeStr", "移库单据创建时间");
            mapFields.put("factoryName", "厂区");
            mapFields.put("warehouseName", "仓库");
            mapFields.put("username", "创建人");

            DeriveExcel.exportExcel(sheetName, moveStorageDetailService.getDetailExcelList(map), mapFields, response, "");
            logService.logInsert("移库单管理导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
